import 'dart:ffi';
import 'dart:ui';
import 'package:magic_car/util/config.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class BevipPage extends StatefulWidget {
  BevipPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<BevipPage> {
  Map acountinfo = new Map();

  String balance = "0.00";
  String chargemoney = "0.00";
  String total_money = "0.00";
  bool showtotal = false;

  List moneylist = [
    {'value': '580', 'select': '0', 'des': '系统（580.00）'},
    {'value': '1198', 'select': '0', 'des': '漆膜仪（1198.00）'},
  ];
  @override
  void initState() {
    super.initState();
    fluwx.weChatResponseEventHandler.listen((res) {
      print(res);
       if (res.errCode == 0) {
         Toast.show('充值成功', context);
        
         Navigator.of(context).pop();
      } else {
         Toast.show('充值失败', context);
      }
      // if (res is fluwx.WeChatPaymentResponse) {
      //    if (data.errCode == 0) {
      //   Toast.show("支付成功");
        
      //    Navigator.of(context).pop();
      // } else {
      //   Toast.show("支付失败");
      // }
      //   // if (res.isSuccessful) {
      //   //   //支付成功
      //   //   Toast.show('充值成功', context);
      //   //   Navigator.pop(context);
      //   //   //loaddata();
      //   // }
      // }
    });
    loaddata(); //页面展示时加载数据
    loadfeeinfo();
  }

//加载信息
  loadfeeinfo() {
//API_BusinessInfo
    Map<String, String> map = new Map();
//map['id']=this.uid;
    HttpHelper.post(HttpHelper.API_BussinessFee, (data) {
      if (data != null) {
        print(data);

        if (data["code"].toString() == "1") {
          var info = data["info"];
          List temp = [];
          for (var i = 0; i < data['info']['feelist'].length; i++) {
            var item = data['info']['feelist'][i];
            item['select'] = '0';
            temp.add(item);
          }

          setState(() {
            moneylist = temp;
          });
        }
      }
    }, params: map);
  }

  //加载数据
  loaddata() async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = pref.getString('uid');

    print(map);

    HttpHelper.post(HttpHelper.API_BusinessInfo, (data) async {
      if (data != null) {
        print(data);
        print(data["info"].length.toString());
        if (data["code"].toString() == "1") {
          setState(() {
            acountinfo = data["info"];
            balance = data["info"]["balance"];
          });
        }
      }
    }, params: map);
  }

  pay() async {
    int select_num = 0;
    moneylist.forEach((element) {
      if (element['select'] == "1") {
        select_num++;
      }
    });
    if (select_num == 0) {
      Toast.show('请选择充值项目', context);
      return;
    }

    Map<String, String> param = new Map();
    param['money'] = total_money;
    SharedPreferences pref = await SharedPreferences.getInstance();
    param["uid"] = pref.getString('uid');
    param["ctype"] = "1";
    if (select_num > 1) {
      param['buy_machine'] = "1";
    }
    HttpHelper.post(HttpHelper.API_Charger_vip, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        if (data["code"].toString() == "1") {
          var payinfo = data['info'];
          print(payinfo['prepayid']['0']);
          fluwx.payWithWeChat(
              appId: Config.wx_appid,
              partnerId: payinfo['partnerid'],
              prepayId: payinfo['prepayid']['0'],
              packageValue: payinfo['package'],
              nonceStr: payinfo['noncestr'],
              timeStamp: int.parse(payinfo['timestamp']),
              sign: payinfo['sign']);
        } else {
          Toast.show(data['msg'], context);
        }
      }
    }, params: param);
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('会员充值'),
          backgroundColor: Colors.white,
          elevation: 0,
        ),
        body: new Container(
          color: Colors.white,
          child: new ListView(
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 15.0),
                child: new Column(
                  children: <Widget>[
                    // new Container(
                    //     color: Colors.white,
                    //     child: new Column(children: <Widget>[
                    //       new Padding(
                    //         padding:
                    //             new EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
                    //         child: new Center(
                    //           child: new Text(
                    //             '可用余额',
                    //             style: TextStyle(fontSize: 15),
                    //           ),
                    //         ),
                    //       ),
                    //       new Padding(
                    //         padding:
                    //             new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 30.0),
                    //         child: new Center(
                    //           child: new Text(
                    //             balance,
                    //             style: TextStyle(fontSize: 24),
                    //           ),
                    //         ),
                    //       ),
                    //       new Container(
                    //         height: 1,
                    //         color: Color.fromRGBO(239, 239, 239, 1),
                    //       ),

                    //     ])),
                    new Padding(
                        padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
                        child: Align(
                          alignment: Alignment.topLeft,
                          child: Text('立即充值(此充值不可退费)'),
                        )),
                    bulidmoneys(),
                    // new Padding(
                    //     padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
                    //     child: Align(
                    //         alignment: Alignment.bottomLeft,
                    //         child: Container(
                    //           padding: new EdgeInsets.fromLTRB(10, 5, 10, 5),
                    //           // color: Color.fromRGBO(235, 235, 235, 1),
                    //           child: Text(
                    //             '系统 （580.00）',
                    //             style: TextStyle(color: Colors.white),
                    //           ),
                    //           decoration: new BoxDecoration(
                    //             // border: new Border.all(width: 2.0, color: Color.fromRGBO(27, 182, 251, 1)),
                    //             // color: items[i]['select'] == "0"
                    //             //     ? Color.fromRGBO(27, 182, 251, 1)
                    //             //     : Colors.red,
                    //             color: Colors.blue,
                    //             borderRadius: new BorderRadius.all(
                    //                 new Radius.circular(5.0)),
                    //           ),
                    //         ))),
                    // new Padding(
                    //     padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
                    //     child: Align(
                    //         alignment: Alignment.bottomLeft,
                    //         child: Container(
                    //           padding: new EdgeInsets.fromLTRB(10, 5, 10, 5),
                    //           // color: Color.fromRGBO(235, 235, 235, 1),
                    //           child: Text(
                    //             '漆膜仪 （1198.00）',
                    //             style: TextStyle(color: Colors.white),
                    //           ),
                    //           decoration: new BoxDecoration(
                    //             // border: new Border.all(width: 2.0, color: Color.fromRGBO(27, 182, 251, 1)),
                    //             // color: items[i]['select'] == "0"
                    //             //     ? Color.fromRGBO(27, 182, 251, 1)
                    //             //     : Colors.red,
                    //             color: Colors.blue,
                    //             borderRadius: new BorderRadius.all(
                    //                 new Radius.circular(5.0)),
                    //           ),
                    //         ))),
                    new Padding(
                        padding: EdgeInsets.fromLTRB(20, 15, 20, 0),
                        child: Align(
                          alignment: Alignment.bottomLeft,
                          child: new Text(
                            '!开通系统后，使用期限为1年，漆膜仪不能单独购买',
                            style: TextStyle(color: Colors.red, fontSize: 12),
                          ),
                        )),
                    showtotal == true
                        ? new Padding(
                            padding: EdgeInsets.fromLTRB(20, 15, 20, 0),
                            child: Align(
                              alignment: Alignment.bottomLeft,
                              child: new Text(
                                '总计：¥' + total_money,
                                style: TextStyle(
                                    color: Colors.black, fontSize: 16),
                              ),
                            ))
                        : new Container(height: 0),
                    // buildmoney(),
                    new Padding(
                        padding:
                            new EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 10.0),
                        child: new Container(
                          width: double.infinity,
                          height: 40,
                          child: new Material(
                            color: Color.fromRGBO(239, 239, 239, 1),
                            //INK可以实现装饰容器
                            child: new Ink(
                              //用ink圆角矩形
                              // color: Colors.red,
                              decoration: new BoxDecoration(
                                //背景
                                color: Color.fromRGBO(27, 182, 251, 1),
                                //设置四周圆角 角度
                                borderRadius:
                                    BorderRadius.all(Radius.circular(20.0)),
                                //设置四周边框
                                border: new Border.all(
                                    width: 1,
                                    color: Color.fromRGBO(27, 182, 251, 1)),
                              ),
                              child: new InkWell(
                                  //圆角设置,给水波纹也设置同样的圆角
                                  //如果这里不设置就会出现矩形的水波纹效果
                                  borderRadius: new BorderRadius.circular(15.0),

                                  //设置点击事件回调
                                  onTap: () {
                                    pay();
                                  },
                                  child: Container(
                                    //设置 child 居中
                                    alignment: Alignment(0, 0),
                                    height: 40,
                                    width: double.infinity,
                                    //color: Color.fromRGBO(27, 182, 251, 1),
                                    child: Text(
                                      "充值",
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  )),
                            ),
                          ),
                        )),
                  ],
                ),
              ),
            ],
          ),
        ));
  }

  Widget bulidmoneys() {
    List<Widget> tiles = [];
    List items = moneylist;
    Widget content;
    for (var i = 0; i < items.length; i++) {
      tiles.add(
        new Padding(
            padding: EdgeInsets.fromLTRB(20, 15, 20, 0),
            child: Align(
                alignment: Alignment.bottomLeft,
                child: GestureDetector(
                    onTap: () {
                      if (items[i]['select'] == "0") {
                        if (i == 1 && items[0]['select'] == "0") {
                          Toast.show('请先选择系统', context);
                          return;
                        }
                        items[i]["select"] = "1";
                      } else {
                        if (i == 0) {
                          items[1]["select"] = "0";
                        }
                        items[i]["select"] = "0";
                      }

                      setState(() {
                        moneylist = items;
                      });
                      int total = 0;
                      moneylist.forEach((element) {
                        if (element['select'] == "1") {
                          total = total + int.parse(element['value']);
                        }
                      });
                      //double totals = formatNum(total, 2);
                      if (total == 0) {
                        setState(() {
                          showtotal = false;
                          total_money = total.toString() + ".00";
                        });
                      } else {
                        setState(() {
                          showtotal = true;
                          total_money = total.toString() + '.00';
                        });
                      }
                    },
                    child: Container(
                      padding: new EdgeInsets.fromLTRB(10, 5, 10, 5),
                      // color: Color.fromRGBO(235, 235, 235, 1),
                      child: Text(
                        items[i]['des'],
                        style: TextStyle(
                            color: items[i]['select'] == "1"
                                ? Colors.white
                                : Colors.black),
                      ),
                      decoration: new BoxDecoration(
                        // border: new Border.all(width: 2.0, color: Color.fromRGBO(27, 182, 251, 1)),
                        // color: items[i]['select'] == "0"
                        //     ? Color.fromRGBO(27, 182, 251, 1)
                        //     : Colors.red,
                        color: items[i]['select'] == "1"
                            ? Colors.blue
                            : Color.fromRGBO(200, 200, 200, 1),
                        borderRadius:
                            new BorderRadius.all(new Radius.circular(5.0)),
                      ),
                    )))),
      );
    }
    content = new Column(children: tiles);

    return content;
  }

  formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      //小数点后有几位小数
      return (num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    } else {
      return (num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    }
  }

  Widget buildmoney() {
    List<Widget> tiles = [];

    Widget content;

    List items = moneylist;
    print(items);
    // print('图片数组长度'+items.isNotEmpty.toString());
    if (items.length > 0) {
      // tiles.add(new Container(
      //       padding: new EdgeInsets.fromLTRB(60, 0, 20, 0),)
      for (var i = 0; i < items.length + 1; i++) {
        //List temp1 = items[i] as List;
        tiles.add(new Container(
            width: 120,
            height: 50,
            // decoration: new BoxDecoration(
            //   color: Colors.blue,
            //   borderRadius: new BorderRadius.all(new Radius.circular(5.0)),
            // ),
            padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: Padding(
                padding: new EdgeInsets.fromLTRB(20, 10, 20, 10),
                child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode()); //隐藏键盘
                      items[i]["select"] = '1';
                      for (var j = 0; j < items.length; j++) {
                        if (i == j) {
                          items[j]['select'] = '1';
                          setState(() {
                            chargemoney = items[j]['value'];
                          });
                        } else {
                          items[j]['select'] = '0';
                        }
                      }
                      setState(() {
                        moneylist = items;
                      });
                    },
                    child: i == items.length
                        ? TextField(
                            inputFormatters: [
                                WhitelistingTextInputFormatter(
                                    RegExp("[0-9]")), //只允许输入字母
                              ],
                            keyboardType: TextInputType.number,
                            onChanged: (value) {
                              print(value);
                              setState(() {
                                chargemoney = value;
                              });
                            },
                            decoration: InputDecoration(
                              contentPadding: new EdgeInsets.all(4),
                              // contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
                              hintText: '输入金额',
                              enabledBorder: OutlineInputBorder(
                                /*边角*/
                                borderRadius: BorderRadius.all(
                                  Radius.circular(5), //边角为5
                                ),
                                borderSide: BorderSide(
                                  color:
                                      Color.fromRGBO(27, 182, 251, 1), //边线颜色为白色
                                  width: 1, //边线宽度为2
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color:
                                      Color.fromRGBO(27, 182, 251, 1), //边框颜色为白色
                                  width: 1, //宽度为5
                                ),
                                borderRadius: BorderRadius.all(
                                  Radius.circular(5), //边角为30
                                ),
                              ),
                            ))
                        : new Container(
                            height: 50,
                            decoration: new BoxDecoration(
                              // border: new Border.all(width: 2.0, color: Color.fromRGBO(27, 182, 251, 1)),
                              color: items[i]['select'] == "0"
                                  ? Color.fromRGBO(27, 182, 251, 1)
                                  : Colors.red,
                              borderRadius: new BorderRadius.all(
                                  new Radius.circular(5.0)),
                            ),
                            child: Center(
                              child: Text(
                                items[i]['des'],
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                            //  new Column(
                            //   children: <Widget>[
                            //     Center(
                            //       child: Text(items[i]['value']),
                            //     ),
                            //   ],
                          )))));
      }
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }
}
